package com.king.first.app.wc;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class WordCountBySocket {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        DataStreamSource<String> hadoop01 = env.socketTextStream("hadoop01", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> map = hadoop01.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                return Tuple2.of(s, 1);
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> tuple2Tuple2KeyedStream =
                map.keyBy((KeySelector<Tuple2<String, Integer>, String>) stringIntegerTuple2 -> stringIntegerTuple2.f0);

        KeyedStream<Tuple2<String, Integer>, String> tuple2StringKeyedStream = map.keyBy(stringIntegerTuple2 -> stringIntegerTuple2.f0);


        KeyedStream<Tuple2<String, Integer>, String> tuple2StringKeyedStream1 = map.keyBy(new MySelectorWC());

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2Tuple2KeyedStream.sum(1);

        sum.print();

        env.execute();
    }
}

class MySelectorWC implements KeySelector<Tuple2<String, Integer>, String>{
    @Override
    public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
        return stringIntegerTuple2.f0;
    }
}